package www.sofn.com.config;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import www.sofn.com.sys.user.SysUserService;
import www.sofn.com.sys.user.domain.pojo.SysUserPO;

@Slf4j
@Configuration
public class AdminSecurityConfiguration {
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Autowired
    private SysUserService sysUserService;
    @Bean
    public UserDetailsService userDetailsService()  {
        return (String username)-> {
            final SysUserPO sysUserPO = sysUserService.selectUserByUsername(username);
            if (ObjectUtil.isNull(sysUserPO)) {
                log.info("登录用户：{} 不存在.", username);
                throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
            }
            return User.builder().username(sysUserPO.getUsername()).password(sysUserPO.getPassword())
                    .authorities(ArrayUtil.toArray(sysUserService.findResourceCodeByUserId(sysUserPO.getId()), String.class)).build();
        };

    }
}
